import prepose, { statement, extractPattern } from '@/assets/api/global.js'
import inSources from '@/assets/api/source.js'
const state = {
	network: [], //请求信息
	sourceInfo: null
}

const getters = {
	get (state) {
		return state.network
	}
}

const mutations = {
	set (state, network) {
		state.network = network
	}
}

const actions = {
	save ({state, commit}, network) {
		const list = [...state.network]
		list.unshift(network)
		commit('set', list)
	},
	remove ({state, commit}, index) {
		const list = [...state.network]
		list.splice(index, 1);
		commit('set', list)
	},
	clear ({commit}) {
		commit('set', [])
	},
	request ({state,dispatch,rootState},{name, url, req, source, data}) {
		return new Promise(resolve => {
			try{
				let reqInfo = req
				if ( !reqInfo && source ) {
					if ( !state.sourceInfo || state.sourceInfo?.id != source ) {
						const rootRources = rootState.source.source
						const rootSubscribe = rootState.subscribe.subscribe
						const rootAdult = rootState.app.adult
						const sources = inSources.concat(rootRources).filter(s => rootSubscribe.indexOf(s.id) == -1 && (!s.isAdult || rootAdult) )
						const index = sources.findIndex(s => s.id == source)
						state.sourceInfo = sources[index]
					}
					const reqs = state.sourceInfo[name]
					const arr = url ? extractPattern(url, statement) : []
					const reqIndex = arr.filter(item => item.type == '@relation:').map(item => item.data)
					reqInfo = Object.assign({}, reqs[reqIndex.length > 0 ? reqIndex[0] : 0], {source: state.sourceInfo})
				}
				prepose(name, url, reqInfo, data).then(res => {
					if ( res.network && rootState.app.debugger ) dispatch('save', res.network)
					resolve(res)
				})
			}catch(e){
				resolve({code: 400, data: null})
			}
		})
	}
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
	actions
}